package com.example.springbootgraduation.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.springbootgraduation.entity.Menu;
import com.example.springbootgraduation.entity.User;
import com.example.springbootgraduation.service.MenuService;
import com.example.springbootgraduation.service.RoleService;
import com.example.springbootgraduation.utils.TreeNode;
import com.example.springbootgraduation.utils.TreeNodeBuilder;
import com.example.springbootgraduation.vo.DataView;
import com.example.springbootgraduation.vo.MenuVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.*;

//菜单
@Controller
@RequestMapping("/menu")
public class MenuController {

    @Autowired
    private MenuService menuService;

    @Autowired
    private RoleService roleService;

    @RequestMapping("/toMenu")
    public String toMenu(){
        return "menu/menu";
    }

    /**
     * 加载所有的菜单
     * @param menuVo
     * @return
     */
    @RequestMapping("/loadAllMenu")
    @ResponseBody
    public DataView loadAllMenu(MenuVo menuVo){
//        拿到MybatisPlus得page对象
        IPage<Menu> page = new Page<>(menuVo.getPage(),menuVo.getLimit());
        QueryWrapper<Menu> queryWrapper = new QueryWrapper<>();
        //使用lang3的StringUtils
        queryWrapper.like(StringUtils.isNoneBlank(menuVo.getTitle()),"title",menuVo.getTitle());//得到title
        queryWrapper.orderByAsc("ordernum");//根据ordernum升序排序
        menuService.page(page);//做分页查询
        return new DataView(page.getTotal(),page.getRecords());//返回带有分页带有查询条件
    }

    /**
     * 加载下拉菜单数据,初始化下拉树
     */
    @RequestMapping("/loadMenuManagerLeftTreeJson")
    @ResponseBody
    public DataView loadMenuManagerLeftTreeJson(){
//        查询所有菜单
        List<Menu> list = menuService.list();
        List<TreeNode> treeNodes = new ArrayList<>();
        for (Menu menu:list){
            Boolean open =  menu.getOpen() == 1?true:false;//是否展开如果为1展开，否则不展开
            treeNodes.add(new TreeNode(menu.getId(),menu.getPid(),menu.getTitle(),open));
        }
        return new DataView(treeNodes);
    }

    /**
     * 赋值最大的排序码+1
     * 拿到最大的排序码，然后+1
     * 条件查询：倒叙排序，只取一条数据，拿到数据+1即可
     */
    @RequestMapping("/loadMenuMaxOrderNum")
    @ResponseBody
    public Map<String,Object> loadMenuMaxOrderNum(){
//        新建一个HashMap
        Map<String,Object> map= new HashMap<>();
//        创建构造查询器(QueryWrapper)
        QueryWrapper<Menu> queryWrapper = new QueryWrapper();
        queryWrapper.orderByDesc("ordernum");//倒叙排序
        IPage<Menu> page = new Page<>(1,1);//拿到分页对象，当前页的一条数据
        List<Menu> list = menuService.page(page, queryWrapper).getRecords();//拿到所有的数据
        map.put("value",list.get(0).getOrdernum()+1);//将value放进去，获得当前menu菜单的实体，再get到Ordernum排序值，最后+1
        return map;
    }

    /**
     * 新增菜单逻辑
     */
    @RequestMapping("/addMenu")
    @ResponseBody
    public DataView addMenu(Menu menu){//menu 接收前台传过来的表单
        DataView dataView = new DataView();
//        设置type初值
        menu.setType("menu");
        boolean save = menuService.save(menu);
        if (!save){
            dataView.setCode(100);
            dataView.setMsg("菜单插入失败！");
        }
        dataView.setMsg("菜单插入成功！");
        dataView.setCode(200);
        return dataView;

    }

    /**
     * 更新菜单
     */
    @RequestMapping("/updateMenu")
    @ResponseBody
    public DataView updateMenu(Menu menu){
        menuService.updateById(menu);
        DataView dataView = new DataView();
        dataView.setCode(200);
        dataView.setMsg("菜单修改成功！");
        return dataView;
    }

    /**
     * 判断有没有子类Id
     * 没有子类Id，可以删除
     * 有子类Id，不能直接删除
     */
    @RequestMapping("/checkMenuHasChildrenNode")
    @ResponseBody
    public Map<String,Object> checkMenuHasChildrenNode(Menu menu){
        Map<String,Object> map = new HashMap<>();
        QueryWrapper<Menu> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("pid",menu.getId());//通过id查询有没有pid
        List<Menu> list = menuService.list(queryWrapper);
        if (list.size()>0){
            map.put("value",true);//告诉前台后孩子节点
        }else {
            map.put("value",false);//没有孩子节点可以删除
        }
        return map;
    }

    /**
     * 真正的删除
     */
    @RequestMapping("/deleteMenu")
    @ResponseBody
    public DataView deleteMenu(Menu menu){
        menuService.removeById(menu.getId());
        DataView dataView = new DataView();
        dataView.setCode(200);
        dataView.setMsg("删除菜单成功！");
        return dataView;
    }

    /**
     * 加载主页面index的菜单栏，带有层级关系
     * 【不同的用户登录看到不同的菜单栏】 加入查询条件
     */
    @RequestMapping("/loadIndexLeftMenuJson")
    @ResponseBody
    public DataView loadIndexLeftMenuJson(Menu menu ,HttpSession session){

        QueryWrapper<Menu> queryWrapper = new QueryWrapper<>();
        /*查询的所有的菜单栏*/
        List<Menu> list = null;

        /*1、取出session中的用户Id，按照条件查询*/
        /*角色分为了【管理员【条件查询】、老师【条件查询】、学生【条件查询】】*/
        User user =(User) session.getAttribute("user");//拿到user对象
        Integer userId = user.getId();//拿到user的id

        if (user.getUsername().equals("admin") || StringUtils.equals(user.getUsername(),"admin")){
            list = menuService.list();
        }else {
            /*2、根据用户Id查询角色Id*/
            List<Integer> currentUserRoleIds = roleService.queryUserRoleById(userId);//当前所拥有的所有ID
            /*3、去除重复的*/
            Set<Integer> mids = new HashSet<>();
            for (Integer rid : currentUserRoleIds){
                /*3.1、根据角色Id查询菜单栏Id*/
                List<Integer> permissionIds = roleService.queryAllPermissionByRid(rid);
                /*3.2、菜单栏Id和角色Id去重*/
                mids.addAll(permissionIds);
            }
            /*4、根据角色Id查询菜单栏*/
            if (mids.size()>0){
                queryWrapper.in("id",mids);
                list = menuService.list(queryWrapper);//根据id查询所有的菜单栏
            }
        }
        /*构造层级关系*/
        List<TreeNode> treeNodes = new ArrayList<>();
        for (Menu m : list){
            Integer id = m.getId();
            Integer pid = m.getPid();
            String title = m.getTitle();
            String icon = m.getIcon();
            String href = m.getHref();
            boolean open = m.getOpen().equals(1) ? true : false;//1为打开，否则为关闭
            treeNodes.add(new TreeNode(id,pid,title,icon,href,open));//树的存储节点
        }
        //构造层级关系
        List<TreeNode> nodeList = TreeNodeBuilder.build(treeNodes, 0);//只要为0节点多是父节点
        return new DataView(nodeList);

    }
}
